<template>
  <div>
    <el-form label-position="top">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="收款平台">
            <el-select v-model="queryParams.payType" clearable placeholder="请选择收款平台" multiple>
              <el-option v-for="item in payList" :value="item.typeId" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <accoutSelect  :inline-block="false" v-model="queryParams.accountIds" :isClient="isClient || isManager" />
        </el-col>
        <el-col :span="6">
          <el-form-item label="轮询组" prop="groupIds" v-if="!isClient">
            <el-select v-model="queryParams.groupIds" filterable multiple clearable  >
              <el-option v-for="item in groupList" :label="item.groupName" :value="item.groupId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商户名称" prop="clientId" v-if="!isClient">
            <el-select v-model="queryParams.clientId" filterable multiple clearable  >
              <el-option v-for="item in clientList" :label="item.userName" :value="item.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="应用ID">
            <el-select v-model="queryParams.appId" multiple filterable clearable  >
              <el-option v-for="item in appList" :label="item.appId" :value="item.appId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收款平台备注" prop="groupTypeRemark" v-if="!isClient">
            <el-input v-model="queryParams.groupTypeRemark" placeholder="请输入收款平台备注" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="创建时间">
            <el-date-picker v-model="queryParams.dateTime" type="datetimerange" range-separator="To"
              start-placeholder="Start date" end-placeholder="End date" style="width: 280px" clearable
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
          </el-form-item>
        </el-col>
        <el-col class="operation_btn" :span="6">
          <el-tooltip class="item" effect="dark" content="重置" placement="top">
              <el-button circle icon="Refresh" @click="refresh" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="查询" placement="top">
              <el-button type="primary" circle icon="Search" @click="getData" />
            </el-tooltip>
        </el-col>
      </el-row>

      <!-- <el-form-item label="收款账号" v-if="!isClient">
          <el-select v-model="queryParams.accountIds" filterable clearable placeholder="请填写收款账号" multiple>
            <el-option v-for="item in accountList" :value="item.accountId" :label="item.accountName"></el-option>
          </el-select>
        </el-form-item> -->
    </el-form>
    <div class="flex items-center text-[14px] text-[#999] font-bold">
      <span>系统汇率更新时间：北京时间 {{ updateTimeInfo }}</span>
      <span class="ml-[50px]">系统时区 Asia/Shanghai UTC+08:00</span>
    </div>

    <NumberDiv :sesstingList="totalSearchList" :settleData="settleData" :is-client="isClient"
      :take-order="queryParams.isFeign" />
    <SuccessRate ref="SuccessRateRef" class="mt-[40px]" :query-params="queryParams" :sesstingList="totalSearchList" />
    <OrderNumber ref="orderNumberRef" class="mt-[40px]" :date-time-list="dateTimeList"
      :sessting-list="totalSearchList" />
    <OrderMoney ref="orderMoneyRef" class="mt-[40px]" :date-time-list="dateTimeList" :sessting-list="totalSearchList" />

    <Ranking v-if="!isClient" class="mt-[40px]" />

    <div class="settings" @click="drawer = true">
      <svg-icon class="icon" icon-class="settings"></svg-icon>
    </div>

    <!-- 设置配置项 -->
    <el-drawer v-model="drawer" :close-on-click-modal="true" title="筛选配置" direction="rtl">
      <el-form>
        <el-form-item v-if="!isClient && isFeign">
          <el-switch v-model="takeOrder"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: var(--el-color-primary)" active-text="商户查看"
            inactive-text="管理员查看" active-value="0" inactive-value="1"></el-switch>
        </el-form-item>
        <!-- <el-form-item label="支付状态">
          <el-checkbox-group v-model="payStatus" @change="changeCheck">
            <el-checkbox v-for="dict in payStatusList" :label="dict.label" :value="dict" />
          </el-checkbox-group>
        </el-form-item> -->

        <el-form-item label="争议状态">
          <el-checkbox-group v-model="disputeStatus" @change="changeCheck">
            <el-checkbox v-for="dict in disputesStatusList" :label="dict.label" :value="dict" />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="退款状态">
          <el-checkbox-group v-model="refundStatus" @change="changeCheck">
            <el-checkbox v-for="dict in refundStatusList" :label="dict.label" :value="dict" />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="物流状态">
          <el-checkbox-group v-model="trackStatus" @change="changeCheck">
            <el-checkbox v-for="dict in logisticsStatusList" :label="dict.label" :value="dict" />
          </el-checkbox-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import accoutSelect from '@/components/AccountSelect';
import { listPayAccount } from '@/api/pay/PayAccount';
import { queryListPayApp } from '@/api/pay/PayApp';
import { getNumberList, getStatusNum, getUpdateTime } from '@/api/index';
import { useDebounceFn } from '@vueuse/core';
import useUserStore from '@/store/modules/user';
import { useDateFormat, useNow } from '@vueuse/core';
import { selecTypetList } from '@/api/pay/PayType/index';
import NumberDiv from './homeComponents/number.vue';
import OrderNumber from './homeComponents/orderNumber.vue';
import OrderMoney from './homeComponents/orderMoney.vue';
import SuccessRate from './homeComponents/successRate.vue';
import Ranking from './homeComponents/ranking.vue';
import { getClient } from '@/api/pay/PayApp';
import { listPayGroup } from '@/api/pay/PayGroup';

const { proxy } = getCurrentInstance();
const updateTimeInfo = ref('');
const getUpdateTimeInfo = async () => {
  let res = await getUpdateTime();
  updateTimeInfo.value = res.data;
};
getUpdateTimeInfo();
const payStatusList = computed(() => {
  return [
    {
      dataValue: 'status_4',
      title: '风险订单',
      label: '风险订单',
      number: 0,
      money: 0,
      value: 4
    }
  ];
});

const { logistics_status } = toRefs(proxy?.useDict('logistics_status'));
const logisticsStatusList = computed(() => {
  logistics_status.value.map((item, index) => {
    item.dataValue = 'track_' + item.value;
    item.icon = item.remark;
    item.title = item.label;
    item.number = 0;
    item.money = 0;
    return item;
  });
  return logistics_status.value;
});

const { refund_status } = toRefs(proxy?.useDict('refund_status'));
const refundStatusList = computed(() => {
  let arr = refund_status.value.filter((item) => {
    item.dataValue = 'refund_' + item.value;
    item.icon = item.remark;
    item.title = item.label;
    item.number = 0;
    item.money = 0;
    return item.label != '退款成功';
  });
  return arr;
});

const { disputes_status } = toRefs(proxy?.useDict('disputes_status'));
const disputesStatusList = computed(() => {
  disputes_status.value.map((item) => {
    item.dataValue = 'dispute_' + item.value;
    item.icon = item.remark;
    item.title = item.label;
    item.number = 0;
    item.money = 0;
    return item;
  });
  return disputes_status.value;
});
const isClient = computed(() => {
  const { isClient } = useUserStore();
  return isClient;
});

const isManager = computed(() => {
  const { isManager } = useUserStore();
  console.log(isManager);
  return isManager;
});

const isFeign = computed(() => {
  const { isFeign } = useUserStore();
  return isFeign;
});

const queryParams = reactive({
  payType: [],
  clientId: [],
  dateTime: [],
  appId: [],
  startTime: '',
  endTime: '',
  isFeign: true,
  status: [],
  disputeStatus: [],
  refundStatus: [],
  trackStatus: []
});
const disputeStatus = ref([]);
const refundStatus = ref([
  {
    dataValue: 'refund_2',
    title: '退款成功',
    label: '退款成功',
    number: 0,
    money: 0,
    value: 2,
    icon: 'refund_success'
  }
]);
const trackStatus = ref([]);
const payStatus = ref([
  {
    dataValue: 'status_4',
    title: '风险订单',
    label: '风险订单',
    number: 0,
    money: 0,
    value: 4,
    icon: 'exposures_order'
  }
]);
const drawer = ref(false);
const takeOrder = ref('');
const sesstingList = ref([]);
// 初始展示搜索列表
const initSearchList = ref([
  {
    dataValue: 'total',
    title: '有效订单',
    number: 0,
    rate: 0,
    transformRate: '',
    icon: 'total_order'
  },
  {
    dataValue: 'status_1',
    title: '弃单',
    number: 0,
    money: 0,
    icon: 'creating'
  },
  {
    dataValue: 'status_2',
    title: '支付成功',
    number: 0,
    money: 0,
    icon: 'pay_success'
  },
  {
    dataValue: 'status_3',
    title: '支付失败',
    number: 0,
    money: 0,
    icon: 'pay_error'
  }
]);
// 扩展搜索列表
const extrasSearchList = reactive([
  {
    title: '支付状态',
    list: [
      {
        title: '风险订单',
        info: {
          number: 20,
          rate: 10,
          icon: 'exposures_order'
        }
      }
    ]
  },
  {
    title: '争议状态',
    list: [
      {
        title: '争议中',
        info: { number: 20, rate: 10, icon: 'disputes' }
      },
      {
        title: '争议成功',
        info: { number: 20, rate: 10, icon: 'disputes_success' }
      },
      {
        title: '争议失败',
        info: { number: 20, rate: 10, icon: 'disputes_error' }
      }
    ]
  },
  {
    title: '退款状态',
    list: [
      {
        title: '退款中',
        info: { number: 20, rate: 10, icon: 'refunding' }
      },
      {
        title: '退款成功',
        info: { number: 20, rate: 10, icon: 'refund_success' }
      },
      {
        title: '退款失败',
        info: { number: 20, rate: 10, icon: 'refund_error' }
      }
    ]
  },
  {
    title: '物流状态',
    list: [
      {
        title: '未推送',
        info: { number: 20, rate: 10, icon: 'not_pushed' }
      },
      {
        title: '推送成功',
        info: { number: 20, rate: 10, icon: 'push_success' }
      },
      {
        title: '推送失败',
        info: { number: 20, rate: 10, icon: 'push_error' }
      }
    ]
  }
]);

const SuccessRateRef = ref(null);
// 总体搜索列表

// 处理参数
const totalSearchList = ref([]);
const changeCheck = () => {
  isChange.value = true;
};

const isChange = ref(true);
const submitForm = async () => {
  drawer.value = false;
  await getData();
};
const resetForm = async () => {
  payStatus.value = [
    {
      dataValue: 'status_4',
      title: '风险订单',
      label: '风险订单',
      number: 0,
      money: 0,
      value: 4,
      icon: 'exposures_order'
    }
  ];
  takeOrder.value = isFeign.value && !isClient.value ? '1' : '0';
  trackStatus.value = [];
  refundStatus.value = [
    {
      dataValue: 'refund_2',
      title: '退款成功',
      label: '退款成功',
      number: 0,
      money: 0,
      value: 4,
      icon: 'refund_success'
    }
  ];
  disputeStatus.value = [];
  drawer.value = false;
  await getData();
};
const refresh = () => {
  queryParams.accountIds = [];
  Object.assign(queryParams, {
    payType: [],
    clientId: [],
    dateTime: [],
    appId: [],
    groupIds: [],
    groupTypeRemark: '',
    startTime: '',
    endTime: '',
    isFeign: takeOrder.value == '0' ? false : true,
    status: [],
    disputeStatus: [],
    refundStatus: [
      {
        dataValue: 'refund_2',
        title: '退款成功',
        label: '退款成功',
        number: 0,
        money: 0,
        value: 4,
        icon: 'refund_success'
      }
    ],
    trackStatus: []
  });
  getData();
};
let loadingServe = null;
const settleData = ref({
  dataValue: 'refund_2',
  title: '退款成功',
  label: '退款成功',
  number: 0,
  money: 0,
  value: 4,
  icon: 'refund_success'
});
const getData = useDebounceFn(async () => {
  loadingServe = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.7)'
  });

  if (takeOrder.value == '0') {
    initSearchList.value = initSearchList.value.filter((item) => item.title != '吃单统计');
  } else {
    initSearchList.value = initSearchList.value.filter((item) => item.title != '吃单统计');
    initSearchList.value.splice(4, 0, {
      title: '吃单统计',
      number: 0,
      money: 0,
      icon: 'take_order',
      dataValue: 'eat'
    });
  }

  if (takeOrder.value == '0') {
    queryParams.isFeign = false;
  } else {
    queryParams.isFeign = true;
  }
  totalSearchList.value = totalSearchList.value.map((item) => {
    item.number = 0;
    item.sucessRate = 0;
    item.count = 0;
    item.money = 0;
    return item;
  });
  queryParams.status = payStatus.value.map((item) => item.value);
  queryParams.disputeStatus = disputeStatus.value.map((item) => item.value);
  queryParams.refundStatus = refundStatus.value.map((item) => item.value);
  queryParams.trackStatus = trackStatus.value.map((item) => item.value);
  totalSearchList.value = initSearchList.value
    .concat(payStatus.value)
    .concat(disputeStatus.value)
    .concat(refundStatus.value)
    .concat(trackStatus.value);
  // 时间筛选条件
  if (queryParams.dateTime && queryParams.dateTime.length) {
    if (useDateFormat(queryParams.dateTime[0], 'YYYY-MM-DD HH:mm:ss').value == useDateFormat(queryParams.dateTime[1], 'YYYY-MM-DD HH:mm:ss').value) {
      ElMessage.error('日期范围不能相同');
      queryParams.dateTime = [];
      return false;
    }
    queryParams.startTime = useDateFormat(queryParams.dateTime[0], 'YYYY-MM-DD HH:mm:ss').value;
    queryParams.endTime = useDateFormat(queryParams.dateTime[1], 'YYYY-MM-DD HH:mm:ss').value;
  } else {
    queryParams.startTime = '';
    queryParams.endTime = '';
  }
  try {
    await getOrderCharts();
    await getNumber();
    isChange.value = false;
  } finally {
    loadingServe.close();
  }
}, 500);

/**获取支付平台 */
const payList = ref([]);
const payConfig = ref([]);
const getPayList = async () => {
  let res = await selecTypetList();
  payList.value = res.data;
};
const loading = ref(false);

const getNumber = async () => {
  //组件更新数据
  SuccessRateRef.value.getData();
  let res = await getNumberList(queryParams);
  if (res.code == 200) {
    if (res.data.sett) {
      settleData.value = {
        number: res.data.sett.count,
        money: Number(res.data.sett.money),
        rate: Number(res.data.sett.successRate),
        transformRate: Number(res.data.sett.transformRate)
      };
    }

    totalSearchList.value.map((item) => {
      if (res.data[item.dataValue]) {
        item.number = res.data[item.dataValue].count;
        item.money = Number(res.data[item.dataValue].money);
        item.rate = Number(res.data[item.dataValue].successRate);
        item.transformRate = Number(res.data[item.dataValue].transformRate);
      }
      return item;
    });
  }
};

// 订单数量/订单金额
const orderNumberRef = ref(null);
const orderMoneyRef = ref(null);
let dateTimeList = ref([]);
const getOrderCharts = async () => {
  let res = await getStatusNum(queryParams);
  if (res.code == 200) {
    dateTimeList.value = await Object.keys(res.data.moneyMap);
    let mkeys = {};
    totalSearchList.value.map((item) => {
      mkeys[item.dataValue] = [];
      return item;
    });
    for (const key in res.data.moneyMap) {
      for (const keyKey in res.data.moneyMap[key]) {
        if (mkeys[keyKey]) {
          mkeys[keyKey].push(res.data.moneyMap[key][keyKey]);
        }
      }
    }

    let nkeys = {};
    totalSearchList.value.map((item) => {
      nkeys[item.dataValue] = [];
      return item;
    });
    for (const key in res.data.numMap) {
      for (const keyKey in res.data.numMap[key]) {
        if (nkeys[keyKey]) {
          nkeys[keyKey].push(res.data.numMap[key][keyKey]);
        }
      }
    }
    totalSearchList.value.map((item) => {
      item.orderNumData = nkeys[item.dataValue];
      item.orderMoneyData = mkeys[item.dataValue];
      return item;
    });
    setTimeout(() => {
      orderNumberRef.value.init();
      orderMoneyRef.value.init();
    }, 200);
  }
};

//获取商户列表
const clientList = ref([]);
const getClientList = async () => {
  if (!isClient.value) {
    let res = await getClient({ roleKey: 'client' });
    clientList.value = res.data;
  }
};

const appList = ref([]);
const getAppList = async () => {
  let res = await queryListPayApp({ pageSize: 200, pageNum: 1 });
  appList.value = res.data;
};

const accountList = ref([]);
const getAccount = () => {
  if (!isClient.value) {
    listPayAccount({ pageSize: 2000, pageNum: 1 }).then((res) => {
      accountList.value = res.rows;
    });
  }
};

// 轮询组列表
const groupList = ref([]);
const getGroupList = async () => {
  if (!isClient.value) {
    let res = await listPayGroup();
    groupList.value = res.rows;
  }
};

onMounted(() => {
  getAppList();
  getClientList();
  getPayList();
  getGroupList();
  if (isFeign.value && !isClient.value) {
    takeOrder.value = '1';
  } else {
    takeOrder.value = '0';
  }

  getData();
});
</script>

<style lang="scss" scoped>
.settings {
  width: 50px;
  height: 50px;
  background-color: var(--el-color-primary-light-3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  color: #fff;
  cursor: pointer;
  position: fixed;
  right: 30px;
  bottom: 10vh;
  z-index: 999;
  animation: moveRotate 2s linear infinite;
  box-shadow: 0px 0px 40px 0px rgba(0, 0, 0, 0.3);
}

@keyframes moveRotate {
  100% {
    transform: rotate(360deg);
  }

  0% {
    transform: rotate(0);
  }
}

:deep(.el-form-item__label) {
  display: inline-block;
  width: fit-content;
}
.operation_btn{
  display: flex;
  align-items: center;
}


</style>
